package com.imglib;

import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.DrawableRes;
import androidx.annotation.NonNull;

import com.aivin.lib_image_load.R;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import com.imglib.bean.ImageInfo;
import com.imglib.bean.LoadStrategy;
import com.imglib.view.ImagePreviewActivity;

/**
 * description:
 */
public class ImagePreviewManager {

    // region 变量
    /**
     * 触发双击的最短时间，小于这个时间的直接返回
     */
    private static final int MIN_DOUBLE_CLICK_TIME = 1500;
    /**
     * 防止多次快速点击，记录上次打开的时间戳
     */
    private long lastClickTime = 0;
    private WeakReference<Context> contextWeakReference;
    /**
     * 图片数据集合
     */
    private List<ImageInfo> imageInfoList;
    /**
     * 用于过度动画的 VIEW
     */
    private View transitionView;
    /**
     * 过度动画的共享元素名
     */
    private String transitionShareElementName;
    /**
     * 动画持续时间 单位毫秒 ms
     */
    private int zoomTransitionDuration = 200;
    /**
     * 默认显示第几个
     */
    private int index = 0;
    /**
     * 下载到的文件夹名（根目录中）
     */
    private String folderName = "";
    /**
     * 最小缩放倍数
     */
    private float minScale = 1.0f;
    /**
     * 中等缩放倍数
     */
    private float mediumScale = 3.0f;
    /**
     * 最大缩放倍数
     */
    private float maxScale = 5.0f;
    /**
     * 是否显示图片指示器（1/9）
     */
    private boolean isShowIndicator = true;
    /**
     * 是否显示关闭页面按钮
     */
    private boolean isShowCloseButton = false;
    /**
     * 是否显示下载按钮
     */
    private boolean isShowDownButton = true;

    /**
     * 是否启用下拉关闭，默认不启用
     */
    private boolean isEnableDragClose = false;
    /**
     * 是否启用上拉关闭，默认不启用
     */
    private boolean isEnableUpDragClose = false;
    /**
     * 是否忽略缩放启用拉动关闭。默认false，true即忽略
     */
    private boolean isEnableDragCloseIgnoreScale = false ;

    /**
     * 是否在加载失败时显示toast
     */
    private boolean isShowErrorToast = false ;

    /**
     * 加载策略
     */
    private LoadStrategy loadStrategy = LoadStrategy.Default;


    /**
     * 顶部指示器背景shape
     */
    private int indicatorShapeResId = R.drawable.shape_indicator_bg;
    /**
     * 设置关闭按钮图片资源
     */
    private int closeIconResId = R.mipmap.ic_action_close;
    /**
     * 设置下载按钮图片资源
     */
    private int downIconResId = R.mipmap.icon_download_new;
    /**
     * 加载失败时的占位图
     */
    private int errorPlaceHolder = R.mipmap.load_failed;



    // endregion

    // region 对外接口
    public static ImagePreviewManager getInstance() {
        return SingletonFactory.instance;
    }


    /**
     * 上下文，必须是activity，不需要担心内存泄漏，本框架已经处理好
     */
    public ImagePreviewManager setContext(@NonNull Context context) {
        this.contextWeakReference = new WeakReference<>(context);
        return this;
    }

    public View getTransitionView() {
        return transitionView;
    }

    /**
     * 设置用于过度动画的共享元素view<br/>
     * 需要同时设置 { ImagePreview#setTransitionShareElementName(String)}
     */
    public ImagePreviewManager setTransitionView(View transitionView) {
        this.transitionView = transitionView;
        return this;
    }

    public String getTransitionShareElementName() {
        return transitionShareElementName;
    }

    /**
     * 设置用于过度动画的共享元素name <br/>
     * 需要同时设置 {  ImagePreview#setTransitionView(View)}
     *
     *   public void onClick(View view) {
     *                 ImagePreview.getInstance()
     *                         .setContext(MainActivity.this)
     *                         .setImageList(list2)
     *                         .setIndex(0)
     *                         .setTransitionView(view)
     *                         .setTransitionShareElementName("shared_element_container")
     *                         .start();
     *             }
     */
    public ImagePreviewManager setTransitionShareElementName(String transitionShareElementName) {
        this.transitionShareElementName = transitionShareElementName;
        return this;
    }

    public List<ImageInfo> getImageInfoList() {
        return imageInfoList;
    }


    /**
     * 设置图片列表信息 <br>
     *  包含缩略图 和原图信息
     */
    public ImagePreviewManager setImageInfoList(@NonNull List<ImageInfo> imageInfoList) {
        this.imageInfoList = imageInfoList;
        return this;
    }

    /**
     * 设置图片列表信息 <br>
     *  只包含原图信息
     */
    public ImagePreviewManager setImageList(@NonNull List<String> imageList) {
        ImageInfo imageInfo;
        this.imageInfoList = new ArrayList<>();
        for (int i = 0; i < imageList.size(); i++) {
            imageInfo = new ImageInfo();
            imageInfo.setThumbnailUrl(imageList.get(i));
            imageInfo.setOriginUrl(imageList.get(i));
            this.imageInfoList.add(imageInfo);
        }
        return this;
    }

    public ImagePreviewManager setImage(@NonNull String image) {
        this.imageInfoList = new ArrayList<>();
        ImageInfo imageInfo;
        imageInfo = new ImageInfo();
        imageInfo.setThumbnailUrl(image);
        imageInfo.setOriginUrl(image);
        this.imageInfoList.add(imageInfo);
        return this;
    }

    public int getIndex() {
        return index;
    }

    /**
     * 从第几张图片开始，索引从0开始
     */
    public ImagePreviewManager setIndex(int index) {
        this.index = index;
        return this;
    }

    public boolean isShowDownButton() {
        return isShowDownButton;
    }

    /**
     * 是否显示下载按钮，在页面右下角。默认显示
     */
    public ImagePreviewManager setShowDownButton(boolean showDownButton) {
        isShowDownButton = showDownButton;
        return this;
    }

    public boolean isShowCloseButton() {
        return isShowCloseButton;
    }

    /**
     * 是否显示关闭页面按钮，在页面左下角。默认不显示
     */
    public ImagePreviewManager setShowCloseButton(boolean showCloseButton) {
        isShowCloseButton = showCloseButton;
        return this;
    }


    /**
     * 是否显示 “显示原图” 按钮。 <br>
     * 根据不同加载策略，自行判断是否显示查看原图按钮
     */
    public boolean isShowOriginButton(int index) {
        List<ImageInfo> imageInfoList = getImageInfoList();
        if (null == imageInfoList || imageInfoList.size() == 0) {
            return false;
        }

        String originUrl = imageInfoList.get(index).getOriginUrl();
        String thumbUrl = imageInfoList.get(index).getThumbnailUrl();
        if (originUrl.equalsIgnoreCase(thumbUrl)) {
            return false;
        }

        //
        if (loadStrategy == LoadStrategy.Default) {
            return true;
        }

        else if (loadStrategy == LoadStrategy.NetworkAuto) {
            return false;
        }

        else if (loadStrategy == LoadStrategy.AlwaysThumb) {
            return false ;
        }

        else if (loadStrategy == LoadStrategy.AlwaysOrigin) {
            return false;
        }

        else {
            return false;
        }
    }


    /**
     * 下载到的文件夹名
     */
    public String getFolderName() {
        if (TextUtils.isEmpty(folderName)) {
            folderName = "Download";
        }
        return folderName;
    }

    /**
     * 保存的文件夹名称，会在Picture目录进行文件夹的新建。
     * 比如："BigImageView"，会在Picture目录新建BigImageView文件夹)
     */
    public ImagePreviewManager setFolderName(@NonNull String folderName) {
        this.folderName = folderName;
        return this;
    }



    public float getMinScale() {
        return minScale;
    }

    public float getMediumScale() {
        return mediumScale;
    }

    public float getMaxScale() {
        return maxScale;
    }

    public int getZoomTransitionDuration() {
        return zoomTransitionDuration;
    }

    /**
     * 缩放动画时长，单位ms
     */
    public ImagePreviewManager setZoomTransitionDuration(int zoomTransitionDuration) {
        if (zoomTransitionDuration < 0) {
            throw new IllegalArgumentException("zoomTransitionDuration must greater 0");
        }
        this.zoomTransitionDuration = zoomTransitionDuration;
        return this;
    }

    public LoadStrategy getLoadStrategy() {
        return loadStrategy;
    }

    /**
     * 加载策略
     */
    public ImagePreviewManager setLoadStrategy(LoadStrategy loadStrategy) {
        this.loadStrategy = loadStrategy;
        return this;
    }

    public boolean isEnableDragClose() {
        return isEnableDragClose;
    }

    /**
     * 是否启用下拉关闭。默认不启用
     */
    public ImagePreviewManager setEnableDragClose(boolean enableDragClose) {
        isEnableDragClose = enableDragClose;
        return this;
    }

    public boolean isEnableUpDragClose() {
        return isEnableUpDragClose;
    }

    /**
     * 是否启用上拉关闭。默认不启用
     */
    public ImagePreviewManager setEnableUpDragClose(boolean enableUpDragClose) {
        isEnableUpDragClose = enableUpDragClose;
        return this;
    }

    public boolean isEnableDragCloseIgnoreScale() {
        return isEnableDragCloseIgnoreScale;
    }

    /**
     * 是否忽略缩放启用拉动关闭。默认不忽略
     */
    public ImagePreviewManager setEnableDragCloseIgnoreScale(boolean enableDragCloseIgnoreScale) {
        isEnableDragCloseIgnoreScale = enableDragCloseIgnoreScale;
        return this;
    }







    public boolean isShowErrorToast() {
        return isShowErrorToast;
    }

    /**
     * 是否显示加载失败的Toast
     */
    public ImagePreviewManager setShowErrorToast(boolean showErrorToast) {
        isShowErrorToast = showErrorToast;
        return this;
    }

    public int getIndicatorShapeResId() {
        return indicatorShapeResId;
    }

    /**
     * 设置顶部指示器背景shape，默认自带灰色圆角shape
     */
    public ImagePreviewManager setIndicatorShapeResId(int indicatorShapeResId) {
        this.indicatorShapeResId = indicatorShapeResId;
        return this;
    }

    public int getCloseIconResId() {
        return closeIconResId;
    }



    public int getDownIconResId() {
        return downIconResId;
    }

    /**
     * 设置下载按钮图片资源，可不填，默认为库中自带：R.drawable.icon_download_new
     */
    public ImagePreviewManager setDownIconResId(@DrawableRes int downIconResId) {
        this.downIconResId = downIconResId;
        return this;
    }

    public boolean isShowIndicator() {
        return isShowIndicator;
    }

    /**
     * 设置是否显示顶部的指示器（1/9）默认显示
     */
    public ImagePreviewManager setShowIndicator(boolean showIndicator) {
        isShowIndicator = showIndicator;
        return this;
    }

    public int getErrorPlaceHolder() {
        return errorPlaceHolder;
    }

    /**
     * 设置失败时的占位图，默认为库中自带R.drawable.load_failed，设置为 0 时不显示
     */
    public ImagePreviewManager setErrorPlaceHolder(int errorPlaceHolderResId) {
        this.errorPlaceHolder = errorPlaceHolderResId;
        return this;
    }







    public void reset() {
        imageInfoList = null;
        transitionView = null;
        transitionShareElementName = null;
        index = 0;
        minScale = 1.0f;
        mediumScale = 3.0f;
        maxScale = 5.0f;
        zoomTransitionDuration = 200;
        isShowDownButton = true;
        isShowCloseButton = false;
        isEnableDragClose = false;
        isShowIndicator = true;
        isShowErrorToast = false;

        closeIconResId = R.mipmap.ic_action_close;
        downIconResId = R.mipmap.icon_download_new;
        errorPlaceHolder = R.mipmap.load_failed;

        loadStrategy = LoadStrategy.Default;
        folderName = "Download";
        if (contextWeakReference != null) {
            contextWeakReference.clear();
            contextWeakReference = null;
        }
        lastClickTime = 0;
    }

    // endregion

    // region 启动新activity

    /**
     *  开启预览
     *  context.startActivity
     */
    public void start() {
        if (System.currentTimeMillis() - lastClickTime <= MIN_DOUBLE_CLICK_TIME) {
            // -忽略多次快速点击
            return;
        }
        if (contextWeakReference == null) {
            throw new IllegalArgumentException("You must call 'setContext(Context context)' first!");
        }

        Context context = contextWeakReference.get();
        if (context == null) {
            throw new IllegalArgumentException("You must call 'setContext(Context context)' first!");
        }

        if (!(context instanceof Activity)) {
            throw new IllegalArgumentException("context must be a Activity!");
        }

        if (imageInfoList == null || imageInfoList.size() == 0) {
            throw new IllegalArgumentException("Do you forget to call 'setImageInfoList(List<ImageInfo> imageInfoList)' ?");
        }

        if (this.index >= imageInfoList.size()) {
            throw new IllegalArgumentException("index out of range!");
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            if (((Activity) context).isFinishing() || ((Activity) context).isDestroyed()) {
                reset();
                return;
            }
        } else {
            if (((Activity) context).isFinishing()) {
                reset();
                return;
            }
        }

        lastClickTime = System.currentTimeMillis();
        ImagePreviewActivity.activityStart(context);
    }

    // endregion

    // region 内部逻辑

    private static class SingletonFactory  {
        // 由 JVM 来保证线程安全
        private static ImagePreviewManager instance = new ImagePreviewManager();
    }

    // endregion
}